package com.rogerfan.easy.web.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.rogerfan.easy.common.R;

public class WebUtil {

	public static R noUser=new R(false, 520, "not user or timeout");
	public static R loginError=new R(false, 521, "login error");
	public static R unAuth=new R(false, 522, "login error");
	public static boolean isAjaxRequest(ServletRequest request){
		return "XMLHttpRequest"
				.equalsIgnoreCase(((HttpServletRequest) request)
						.getHeader("X-Requested-With"));
	}
	
	
	
	public static void print(ServletResponse response,R r) throws IOException{
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.println( JSON.toJSONString(r));
		out.flush();
		out.close();
	}
	
	public static String getHeader(HttpServletRequest req,String headerName){
		Enumeration<String>  headers =req.getHeaderNames();
		while(headers.hasMoreElements()){
			if(headers.nextElement().equalsIgnoreCase(headerName)){
				String result =req.getHeader(headerName);
				if(StringUtils.isBlank(result)){
					return "";
				}else{
					return result.trim();
				}
			}
		}
		return null;
	}
}
